#include "DRWidgetLeft.h"
#include "ui_DRWidgetLeft.h"

DRWidgetLeft::DRWidgetLeft(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DRWidgetLeft)
{
    ui->setupUi(this);

    panleIndex = 0;
    currentGroup = 0;

    connect(ui->lineEditSearch, SIGNAL(textChanged(QString)), this, SLOT(searchTextChange(QString)));
    connect(ui->pushButtonAdd, SIGNAL(clicked()), this, SLOT(addButtonClicked()));

    searchTextChange("");
}

DRWidgetLeft::~DRWidgetLeft()
{
    delete ui;
}

void DRWidgetLeft::searchGroup(QString text, int index)
{
    QListWidgetItem *item;
    DRListItemGroup *itemGroup;

    item = new QListWidgetItem(ui->listWidgetRecords);
    itemGroup = new DRListItemGroup(text, index, true);
    item->setSizeHint(QSize(ui->listWidgetRecords->width(), itemGroup->height()));
    ui->listWidgetRecords->setItemWidget(item, itemGroup);

    connect(itemGroup, SIGNAL(onDelete(int)), this, SIGNAL(onDeleteGroup(int)));
}

void DRWidgetLeft::searchRecord(DRItemType item1)
{
    QListWidgetItem *item;
    DRListItem      *itemRecord;
    DRListItemGroup *itemGroup;

    if (item1.type)
    {
        item = new QListWidgetItem(ui->listWidgetRecords);
        itemRecord = new DRListItem(item1.index, item1.text, item1.time, true);
        item->setSizeHint(QSize(ui->listWidgetRecords->width(), itemRecord->height()));
        ui->listWidgetRecords->setItemWidget(item, itemRecord);

        connect(itemRecord, SIGNAL(onDelete(int)), this, SIGNAL(onDeleteRecord(int)));
    }
    else
    {
        item = new QListWidgetItem(ui->listWidgetRecords);
        itemGroup = new DRListItemGroup(item1.text, item1.index);
        item->setSizeHint(QSize(ui->listWidgetRecords->width(), itemGroup->height()));
        ui->listWidgetRecords->setItemWidget(item, itemGroup);
    }
}

void DRWidgetLeft::addRecord(DRItemType item1)
{
    QListWidgetItem *item;
    DRListItem      *itemRecord;

    item = new QListWidgetItem(ui->listWidgetRecords);
    itemRecord = new DRListItem(item1.index, item1.text, item1.time);
    item->setSizeHint(QSize(ui->listWidgetRecords->width(), itemRecord->height()));
    ui->listWidgetRecords->setItemWidget(item, itemRecord);

    connect(itemRecord, SIGNAL(onDelete(int)), this, SIGNAL(onDeleteRecord(int)));
}

void DRWidgetLeft::searchTextChange(QString text)
{
    QListWidgetItem *item;
    QWidget         *itemWidget;

    for (int i=ui->listWidgetRecords->count(); i>=0; i--)
    {
        item = ui->listWidgetRecords->takeItem(i);

        itemWidget = ui->listWidgetRecords->itemWidget(item);
        delete item;
        delete itemWidget;
    }

    switch (this->panleIndex)
    {
        case 1:
            emit onSearchRecord(text);
            break;
        case 2:
            emit onSearchGroup(text);
            break;
    }
}

void DRWidgetLeft::addButtonClicked()
{
    emit onAddRecord(currentGroup);
}
